package com.jiuzhe.commercial.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseFragment;
import com.jiuzhe.commercial.base.HouseResTitleItemStruct;
import com.jiuzhe.commercial.bean.HotelstateBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.ui.components.EQComplexTable;
import com.jiuzhe.commercial.ui.components.EQGridCtrl;
import com.jiuzhe.commercial.ui.components.ReportTitleStruct;
import com.jiuzhe.commercial.ui.components.TableBaseObj;
import com.jiuzhe.commercial.ui.house.CalendarActivity2;
import com.jiuzhe.commercial.utils.DateUtils;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 12078 on 2018/4/19.
 */

public class HomeFragment extends BaseFragment implements TableBaseObj.EQTableOnListener {
    EQComplexTable table;
    private EQGridCtrl mGridCtrl;
    ReportTitleStruct myTitleData;
    TextView mHeadTitle;
    ImageView mIbLocation,ivNot;
    ImageView mIbSwitcher,mIbAdd;
    private int REQUEST_CODE = 0;
    private List<List<HotelstateBean.BodyBean>> body = new ArrayList<>();
    private List<HotelstateBean.HeadBean> head = new ArrayList<>();
    private List<HotelstateBean.LeftBean> left = new ArrayList<>();

    String resultJson;
    ViewGroup fragmentView;
    int year;
    private LinearLayout linearLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (fragmentView != null) {
            return fragmentView;
        }
        fragmentView = (ViewGroup) inflater.inflate(getLayoutResource(), container, false);
        table = new EQComplexTable(getContext());
        table.setEQTableOnListener(this);
        table.setEQRootView(fragmentView);
        mGridCtrl = fragmentView.findViewById(R.id.grid_ctrl);
        mHeadTitle = fragmentView.findViewById(R.id.head_title);
        mIbLocation = fragmentView.findViewById(R.id.ib_location);
        mIbAdd = fragmentView.findViewById(R.id.ib_add);
        mIbSwitcher = fragmentView.findViewById(R.id.ib_switcher);
        linearLayout = fragmentView.findViewById(R.id.ll_switcher);
        ivNot = fragmentView.findViewById(R.id.iv_not);
        table.setmGridCtrl(mGridCtrl);
        mHeadTitle.setText("房态");
        mIbLocation.setVisibility(View.GONE);
        mIbAdd.setVisibility(View.GONE);
        initView();
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        return fragmentView;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.room_status_fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    private void initView() {
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CalendarActivity2.class);
                intent.putExtra("from", "MainActivity");
                startActivityForResult(intent, REQUEST_CODE);
//                UIUtils.startActivity(CalendarActivity2.class);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            initData();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private void initData() {
        // 获取日期选择参数，根据更新条件更新表格
        // 更新条件：是否点击日期选择确定按钮、是否记录当前滚动位置
        getCalendarData();

        //首先只加载表头
        loadTitles();

        //请求表头、请求表内容
        requestExtraTitles();

        //更新表头
        // updateGridHead();

        //加载表内容
//         loadGridBody();
    }

    private void loadGridBody() {
        table.notifiedPageFillView(head, body, left);
    }

    private void updateGridHead() {
        myTitleData = produceTitlesData();
        table.setReportTitleStruct(myTitleData);
    }

    private ReportTitleStruct produceTitlesData() {
        HouseResTitleItemStruct houseResTitles = new HouseResTitleItemStruct();
        houseResTitles.setData(head);
        return adaptToTitleStruct(houseResTitles);
    }

    private ReportTitleStruct adaptToTitleStruct(HouseResTitleItemStruct houseResTitles) {
        int size = head.size();
        for (int i = 0; i < size; i++) {
            head.get(i).setId((i + 1) + "");
        }
        List<HotelstateBean.HeadBean> dataBean = houseResTitles.getData();
        ReportTitleStruct struct = new ReportTitleStruct();
        int length = dataBean.size() + 1;
        ReportTitleStruct[] titles = new ReportTitleStruct[length];
        for (int i = 0; i < length; i++) {
            titles[i] = new ReportTitleStruct();
            if (i == 0) {
                titles[i].setmTitleName("0");
            } else {
                HotelstateBean.HeadBean data = dataBean.get(i - 1);
                titles[i].setmTitleName(data.getId());
                String week_day = "";
                if (Constants.TIME_ROOM != null) {
                    Date day = Constants.TIME_ROOM.get(i - 1);
                    Date today = Constants.TODAY;
                    if (day.toString().substring(0, 9).equals(today.toString().substring(0, 9))) {
                        week_day = "今";
                    } else {
                        week_day = day.toString().substring(0, 3);
                        week_day = convertChineseDay(week_day);
                    }
                }
                String date = data.getDate();
                String  day_date =  DateUtils.getDateString();
                String  week =  DateUtils.getWeek(date);
                if (date.contains(day_date)){
                    week = "今";
                }
                titles[i].setmTitle(reformat(data.getDate()) + "\n" + week + "\n剩" + data.getFreeNum());
            }
        }
        struct.setmTitleChildren(titles);

        return struct;
    }

    private String convertChineseDay(String week_day_English) {
        String week_day_Chinese = "";
        switch (week_day_English) {
            case "Sun":
                week_day_Chinese = "日";
                break;
            case "Mon":
                week_day_Chinese = "一";
                break;
            case "Tue":
                week_day_Chinese = "二";
                break;
            case "Wed":
                week_day_Chinese = "三";
                break;
            case "Thu":
                week_day_Chinese = "四";
                break;
            case "Fri":
                week_day_Chinese = "五";
                break;
            case "Sat":
                week_day_Chinese = "六";
                break;
            default:
                break;
        }

        return week_day_Chinese;
    }

    private void produceBodyData() {
        loadGridBody();
    }

    private void requestExtraTitles() {

    }

    private void loadTitles() {

    }

    private void getCalendarData() {
        HashMap<String, String> map = new HashMap<>();
       if(Constants.TIME_ROOM != null) {
           List<Long> datesLong = new ArrayList<>();
           List<Date> time = Constants.TIME_ROOM;
           for (Date date : time) {
               datesLong.add(UIUtils.date2Milliseconds(date));
           }
           long maxDate = Collections.max(datesLong);
           long mixDate = Collections.min(datesLong);

           SimpleDateFormat timeFormat = new SimpleDateFormat("MM-dd");
           String startTime = UIUtils.milliseconds2String(mixDate, timeFormat);
           String endTime = UIUtils.milliseconds2String(maxDate, timeFormat);
           map.put("beginDate", year + "-" + startTime);
           map.put("endDate", year + "-" + endTime);
       }else {
           List<String> dates = DateUtils.get7date();

           map.put("beginDate", dates.get(0));
           map.put("endDate", dates.get(13));
       }

        String token = SPUtil.getString(getContext(), Constants.TOKEN);
        String mer_id = SPUtil.getString(getContext(), Constants.MERCHANTID);
        String id = SPUtil.getString(getContext(), Constants.ID);
        String autoSignStr = Constants.HOTELSTATE.substring(Constants.HOTELSTATE.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        map.put("merchantId", mer_id);
     //   map.put("merchantId", "zpy");
        map.put("currentPage", "1");
        map.put("number", "10");
       HttpClient.post(this, Constants.HOTELSTATE, map, new CallBack<HotelstateBean>() {
           @Override
            public void onSuccess(HotelstateBean result) {
                body = result.getBody();
                head = result.getHead();
                left = result.getLeft();
                if (left.size() == 0){
                    ivNot.setVisibility(View.VISIBLE);
                }
               updateGridHead();
               produceBodyData();
            }
       });

      /*  CallBack<HotelstateBean> myCallBack = new CallBack<HotelstateBean>() {
            @Override
            public void onSuccess(HotelstateBean result) {
                body = result.getBody();
                head = result.getHead();
                left = result.getLeft();
                updateGridHead();
                produceBodyData();
            }
        };*/
        //localPost();
        /*try {
          //  JSONObject jsonObject = new JSONObject(resultJson);
          //  String result = jsonObject.getString("data");
          //  myCallBack.onSuccess((HotelstateBean) new Gson().fromJson(result, myCallBack.type));
        } catch (JSONException e) {
            e.printStackTrace();
        }*/
    }

    private void localPost() {
        try {
            InputStream is = getContext().getAssets().open("house_json.txt");
            resultJson = readTextFromSDcard(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String readTextFromSDcard(InputStream is) throws Exception {
        InputStreamReader reader = new InputStreamReader(is, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuffer buffer = new StringBuffer("");
        String str;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
            buffer.append("\n");
        }
        return buffer.toString();//把读取的数据返回
    }

    @Override
    public void setTableHeader(String reportLayerName, ReportTitleStruct titleStruct) {

    }

    @Override
    public void onClickHeaderTitleListener(String reportLayerName, String id, String sortType) {

    }

    @Override
    public ArrayList<String> getColumnId(String reportLayerName, String id) {
        return null;
    }

    @Override
    public void onClickTableContentListener(String reportLayerName, int row) {

    }

    @Override
    public void pullFreshPage(String reportLayerName, int index) {

    }

    @Override
    public void setDate(String reportLayerName, String name, String date) {

    }

    @Override
    public void setSpinner(String reportLayerName, String name, int index) {

    }

    @Override
    public HashMap<String, String> getSortParam(String reportLayerName) {
        return null;
    }

    @Override
    public boolean isSortable(String reportLayerName) {
        return false;
    }

    public static void main(String args[]) {
        String time1 = "2018-06-01";
        int index = time1.indexOf("-");
        String time2 = time1.substring(index + 1);
        System.out.println(time2);
        time2 = time2.replace("0", "");
        System.out.println(time2);
    }

    private String reformat(String input) {
        int index = input.indexOf("-");
        String time2 = input.substring(index + 1);
        String day = time2.substring(3,5);
        if (day.equals("10") || day.equals("20") || day.equals("30")){
            if (time2.startsWith("0")){
                time2 = time2.substring(1, time2.length());
            }
        }else {
                time2 = time2.replace("0", "");
        }
        return time2;
    }
}
